<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
	<title>Document</title>
	<link rel="stylesheet" href="./css/index.css" />
	<link rel="stylesheet" href="./css/iconfont.css" />
	<link rel="stylesheet" href="./css/player.css">
	<link rel="stylesheet" href="./css/iconfont.css" />
	<link rel="stylesheet" href="./css/results.css" />
	<link rel="stylesheet" href="./css/video.css">
	<link rel="stylesheet" href="./css/comment.css">
</head>

<body>
	<div id="player">
		<h2 class="title">黑云音乐</h2>
		<div class="search">
			<input type="text" v-model.trim="musicName" @keyup.enter="searchMusic" />
			<button>
				<span class="iconfont icon-search" @click="searchMusic"></span>
			</button>
		</div>
		<div class="tab-wrapper">
			<!-- tab栏 -->
			<div class="tab-bar">
				<router-link to="/results" active-class="active" class="bar-item">
					搜索结果
				</router-link>
				<router-link to="/player" active-class="active" class="bar-item">
					歌曲播放
				</router-link>
				<router-link to="/video" active-class="active" class="bar-item">
					MV
				</router-link>
				<router-link to="/comment" active-class="active" class="bar-item">
					歌曲评论
				</router-link>

			</div>
			<!-- 对应的内容区域 -->
			<div class="tab-content">
				<!-- 根据路由来展示对应的内容 -->
				<router-view></router-view>
			</div>
		</div>
	</div>
</body>

</html>
<script src="./lib/vue.js"></script>
<script src="./lib/vue-router.js"></script>
<script src="./lib/axios.js"></script>
<!-- 搜索结果组页面 -->
<script type="text/html" id="result">
<div class="result-wrapper">
  <div class="song" v-for="(item,index) in resultList" :key="'song'+index">

    <div class="name">
      <span @click="toPlay(item)" class="iconfont icon-play"></span>
		<a @click.prevent="toComment(item.id)">{{item.name}}</a>
      <span @click="toMv(item.mvid)" v-if="item.mvid!==0" class="iconfont icon-editmedia"></span>
    </div>
    <div class="singer">{{item.artists[0].name}}</div>
    <div class="album">{{item.album.name}}</div>
    <div class="time">{{item.duration | formatTime}}</div>
  </div>
 <div></div>
</div>
</script>
<!-- mv页面 -->
<script type="text/html" id="video">
  <div class="video">
    <div class="title-wrapper">
      <span class="tag">MV</span>
      <span class="title">{{videoInfo.data.data.artistName}}</span>
      <span class="artist">{{videoInfo.data.data.name}}</span>
    </div>
    <video src="" controls> <img :src="videoInfo.data.data.cover"/></video>
  </div>
</script>
<!-- 播放页面 -->
<script type="text/html" id="myplayer">
<div class="player">
  <div class="left">
    <img class="disc" src="./img/disc.png" alt="">
    <img class="cover" :src="albumImg" alt="">
  </div>
  <div class="right">
    <div class="title"><img src="./img/tag.png" alt=""><span>{{title}}</span> </div>
    <div class="singer">歌手: <span>{{singer}}</span></div>
    <div class="album">所属专辑: <span>{{album}}</span></div>
    <audio class="audio" :src="musicUrl" autoplay controls ></audio>
    <ul class="lyric-container">
      <li class="lyric" v-for="(item,index) in lyric" :key="'lyric'+index">{{item}}</li>
    </ul>
  </div>
</div>
</script>
<!-- 评论页面 -->
<script type="text/html" id="comment">
<div class="comment-wrapper">
  <div class="items">
    <div class="item" v-for="(item,index) in commentsList" :key="'comment'+index">
      <div class="left">
        <img :src="item.user.avatarUrl" alt="用户头像">
      </div>
      <div class="right">
        <div class="top">
          <span class="user">{{item.user.nickname}}</span>
          <span
            class="content">{{item.content}}</span>
        </div>
        <div class="bottom">
          <div class="time">{{item.timeStr}}</div>
          <div class="like-wrapper">
            <span>👍</span>{{item.likedCount}}
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</script>
<script>
	axios.defaults.baseURL = "https://autumnfish.cn"
	axios.default.timeout = 4000
	// 搜索结果组件
	const Result = {
		template: '#result',
		data() {
			return {
				// 保存搜索的结果
				resultList: []
			}
		},
		// 在当前组件进行渲染时就发出数据请求
		created() {
			this.getSongList();
		},
		// 对其进行监听
		watch: {
			'$route.params.music': function () {
				this.getSongList()
			}
		},
		methods: {
			async getSongList() {
				// data.result.songs
				// 当调用当前函数时判断路由传递的参数是否为空 如果有路由传递过来的参数，那么就是用该参数，否则就使用本地存储的
				// 在这里是为了判断用户是通声明式导航点击过来的还是通过输入框点击搜索过来的
				let music = this.$route.params.music ? this.$route.params.music : window.localStorage.getItem("keyword")
				let response = await axios.get(`https://autumnfish.cn/search?keywords=${music}`)
				this.resultList = response.data.result.songs

			},
			// 列表页的播放按钮
			toPlay(item) {
				// 点击播放之后就将歌曲的id通过路由传参，传递给另一个组件
				localStorage.setItem('songInfo', JSON.stringify(item))
				router.push(`/player/${item.id}`)
			},
			// 跳转到mv页面的点击事件
			toMv(item) {
				// 将点击歌曲的相关信息通过路由传参传递过去
				router.push(`/video/${item}`)
			},
			// 跳转到评论页面的播放按钮
			toComment(item) {
				// 将点击歌曲的当前信息通过路由传参传递过去
				router.push(`/comment/${item}`)
			}
		},
		filters: {
			// 对歌曲的持续时间进行处理，将传递过来的持续时间(ms)转换为多少分多少秒的格式
			formatTime(time) {
				const totalSec = time / 1000;
				const min = parseInt(time / 1000 / 60);
				let sec = parseInt(time / 1000 % 60);
				sec = sec < 10 ? '0' + sec : sec;
				return min + ':' + sec;
			}
		}
	}
	// 播放歌曲组件
	const Player = {
		template: '#myplayer',
		data() {
			return {
				// 音乐地址
				musicUrl: '',
				// 歌曲标题
				title: '',
				// 歌手名字
				singer: '',
				// 封面地址
				albumImg: '',
				// 专辑
				album: '',
				// 歌词
				lyric: []
			}

		},
		async created() {
			let id = this.$route.params.id;
			if (!id) {
				alert('非法访问!');
				history.back();
				return;
			}
			// 发送请求，获取歌曲地址
			this.musicUrl = `https://music.163.com/song/media/outer/url?id=${id}.mp3 `
			let songInfo = JSON.parse(localStorage.getItem('songInfo'));
			this.title = songInfo.name;
			this.album = songInfo.album.name;
			let singers = songInfo.artists;
			// 如果是多个歌手的话就将它们的名字用空格隔开
			let sing = '';
			singers.forEach((item) => {
				sing += item.name + ' '
			})
			sing.trim()
			this.singer = sing;
			let cover = await axios(`/album?id=${songInfo.album.id}`)
			this.albumImg = cover.data.album.picUrl;
			// 获取歌词
			let lyric = await axios.get('/lyric?id=' + id);
			// 获取到的个词是一个字符串，将字符串按照换行符进行切分
			let result = lyric.data.lrc.lyric.split('\n');
			// 将列表中的歌词每一项都将前面的时长用空白符替换掉
			let list = result.map((item) => {
				// 要注意map有返回值，所以这里需要使用return
				return item.replace(/\[.*?\]/, '')
			})
			this.lyric = list
		}
	}
	// mv组件
	const Videos = {
		template: '#video',
		data() {
			return {
				// 视频信息
				videoInfo: '',
			}
		},
		async created() {
			let id = this.$route.params.mvid;
			if (!id) {
				alert('非法访问!');
				history.back();
				return;
			}
			let res = await axios(`/mv/detail?mvid=${id}`);
			this.videoInfo = res
		}
	}
	// 评论组件
	const Comment = {
		template: '#comment',
		data() {
			return {
				// 评论相关信息
				commentsList: []
			}
		},
		async created() {
			let id = this.$route.params.id;
			if (!id) {
				alert('非法访问!');
				history.back();
				return;
			}
			let res = await axios(`/comment/hot?id=${id}&type=0`);
			this.commentsList = res.data.hotComments;
		}
	}

	// router实例化
	let router = new VueRouter({
		routes: [
			// :music表示将music通过路由传递过去，后面的问号代表可有可无
			{ path: '/', redirect: '/results/海阔天空' },
			{ path: '/results/:music?', component: Result },
			{ path: '/player/:id?', component: Player },
			{ path: '/video/:mvid?', component: Videos },
			{ path: '/comment/:id?', component: Comment },
		]
	})
	// 挂载roter实例化到vue上
	new Vue({
		el: '#player',
		data: {
			// musicName为用户搜索的音乐名字
			musicName: '',
			musicNameCopy: '',
		},
		router,
		methods: {
			// 搜索音乐
			searchMusic() {
				// 用户的输入内容不能为空
				if (!this.musicName) {
					alert('输入内容不能为空！');
					return
				}
				// 声明式导航与编程式导航的区别与应用
				// 下一步是跳转到result路由
				// let songs=localStorage.getItem(songList)

				this.musicNameCopy = this.musicName
				this.musicName = ''
				localStorage.setItem("keyword", this.musicNameCopy)
				router.push('/results/' + this.musicNameCopy);
			}
		}
	})
</script>